import random, os, uuid, time
from io import BytesIO
from config import config
from alipay import AliPay
from django.shortcuts import redirect, HttpResponse
from django.shortcuts import render
from trade import models
from utils.check_code import create_validate_code
from utils.md5_encryption import md5_string
from utils.select_user_data import select
from utils.updateExcelDomain import updateDomain
from django.views.decorators.csrf import csrf_exempt,csrf_protect
from utils import select_domain,registered_main,sort_registered,\
  buyHistory,modify_domain, search_domain,modify_user_self_info,\
  send_email


# Create your views here.

def auto(func):
  """
  用户登录验证装饰器
  :param func requests:
  :return:
  """
  def wrap(request, *args, **kwargs):
    path = request.get_raw_uri()
    request.session['path'] = path
    # 如果未登陆，跳转到指定页面
    if request.session.get('is_login'):
      return func(request, *args, **kwargs)
    else:
      return redirect('/signin')
  return wrap

def auto_super(func):
  """
  超级用户登录验证装饰器
  :param func requests:
  :return:
  """
  def wrap(request, *args, **kwargs):
    path = request.get_raw_uri()
    request.session['path'] = path
    # 如果未登陆或不是管理员，跳转到指定页面
    if request.session.get('is_login') and \
                    request.session.get('is_super') == 1:
      return func(request, *args, **kwargs)
    else:
      return redirect('/index')

  return wrap

def auto_is_login(request):
  """
  判断当前用户是否登录
  :param request: 请求
  :return:
  """
  is_super = '0'
  if request.session.get('is_login'):
    is_login = '1'
    if request.session.get('is_super'):
      is_super = '1'
  else:
    is_login = '0'
  return is_super, is_login

@csrf_protect
def signin(request):
  """
    登录
    :param request:
    :return:
  """
  msg_tag = ''
  if request.session.get('is_login'):
    return redirect('/index')
  if request.method == 'POST':
    if request.POST.get('check_code').upper() == \
            request.session['CheckCode'].upper():
      username = request.POST.get('email')
      passwd = request.POST.get('passwd')
      if username:
        passwd = md5_string(passwd)
        user_info = models.UsersList.objects.filter(user_email=username).first()
        db_passwd = user_info.password
        is_super = user_info.is_super
        if passwd == db_passwd:
          request.session['username'] = username
          request.session['user_id'] = user_info.id
          request.session['useruuid'] = user_info.uuid
          request.session['is_login'] = True
          if is_super == 1:
            path = request.session.get('path', '/admin')
            request.session['is_super'] = True
            request.session.set_expiry(0)
            return redirect(path)
          else:
            path = request.session.get('path', '/admin')
            request.session['is_super'] = False
            request.session.set_expiry(0)
            return redirect(path)
        else:
          msg_tag = '用户名或密码有误'
      else:
        msg_tag = '用户名或密码有误'
    else:
      msg_tag = '验证码错误'
  return render(request, 'signin.html', {'msg_tag': msg_tag})

def signup(request):
  """
    注册
    :param request:
    :return:
  """
  msg_tag = ''
  if request.method == 'POST':
    email = request.POST.get('email')
    if email:
      if request.session.get(email + '_code') \
              == request.POST.get('email_check_code'):
        passwd = request.POST.get('passwd')
        tel = request.POST.get('tel')
        if passwd:
          passwd = md5_string(passwd)
          if passwd and tel and email:
            uuid_code = uuid.uuid1()
            user_info = {
              'user_email': email,
              'password': passwd,
              'phone': tel,
              'is_super': 0,
              'uuid': uuid_code
            }
            models.UsersList.objects.create(**user_info)
            if models.UsersList.objects.filter(user_email=email):
              return redirect('/signin')
            else:
              msg_tag = '用户注册失败'
        else:
          msg_tag = '密码不能为空'
      else:
        msg_tag = '验证码不正确'
    else:
      msg_tag = '用户不存在'
  return render(request, 'signup.html', {'msg_tag': msg_tag})

def forgetPasswd(request):
  """
  重置密码
  :param request:
  :return:
  """
  msg_tag = ''
  if request.method == "POST":
    email = request.POST.get('email')
    if email:
      if request.session.get(email + '_code') \
              == request.POST.get('email_check_code'):
        db_email = models.UsersList.objects.filter(user_email=email).first()
        if db_email:
          passwd1 = request.POST.get('passwd1')
          passwd2 = request.POST.get('passwd2')
          if passwd1 == passwd2:
            passwd2 = md5_string(passwd2)
            models.UsersList.objects.filter(user_email=email).update(password=passwd2)
            db_passwd = models.UsersList.objects.filter(user_email=email).first().password
            if db_passwd == passwd2:
              return redirect('/signin')
            else:
              msg_tag = '密码修改失败'
          else:
            msg_tag = '密码不匹配'
        else:
          msg_tag = '用户不存在'
      else:
        msg_tag = '验证码输入错误'
    else:
      msg_tag = '用户不存在'
  return render(request, 'repasswd.html', {'msg_tag': msg_tag})

def index(request):
  """
  首页
  :param request:
  :return:
  """
  # 判断用户是否登录
  is_super, is_login = auto_is_login(request)
  if request.method == "GET":
    page_num = request.GET.get('p','1')  #获取p的数值(页数)
    if not page_num.isdecimal():
      page_num = 1
    totle_page = select_domain.get_pages()
    page_num = int(page_num)
    if page_num > totle_page:
      page_num = totle_page
    page_list = select_domain.get_page_list(page_num, totle_page)
    domain_dic = select_domain.get_domian_info(page_num)
  return render(request, 'home.html', {'is_login': is_login, 'is_super': is_super, \
                                       'domain_dic':domain_dic, 'page_list': page_list,\
                                       'totle_page':totle_page, 'now_page':page_num
                                       })

def search(request):
  """
  处理ajax发送的域名筛选
  :param request:
  :return:
  """
  if request.method == 'POST':
    fastSelect = request.POST.get('fastSelect', None)
    keyWord = request.POST.get('keyWord', None)
    startEndKeyWord = request.POST.get('startEndKeyWord', None)
    suffix = request.POST.get('suffix', None)
    buyType = request.POST.get('buyType', None)
    PAGE = request.POST.get('PAGE', 1)
    domain_info = 'error'
    if fastSelect or keyWord or \
            startEndKeyWord or \
            suffix or buyType:
      domain_info = search_domain.searchDoamin(fastSelect=fastSelect,
                                             kewWord=keyWord,
                                             startEndKeyWord= startEndKeyWord,
                                             suffix=suffix,
                                             buyType = buyType, pageNum=PAGE)
      return HttpResponse(str(domain_info))
  return HttpResponse(str(domain_info))

@auto
def signout(request):
  """
  登出
  :param request:
  :return:
  """
  # request.session.clear_expired()
  request.session.clear()
  return redirect('/index')

def check_code(request):
  """
  验证码
  :param request:
  :return:
  """
  stream = BytesIO()
  img, code = create_validate_code()
  img.save(stream, 'PNG')
  request.session['CheckCode'] = code
  return HttpResponse(stream.getvalue())

def sendEmail(request):
  """
  发送邮箱验证码
  :param requests:
  :return:
  """
  if request.method == "GET":
    return HttpResponse('Error')
  if request.method == "POST":
    email = request.POST.get('email')
    if email:
      # ramdom number
      ramNum = ''
      for i in range(6):
        ramNum += str(random.randint(0, 9))
      send_email.send_email(email, ramNum)
      request.session[email + '_code'] = ramNum
      request.session.set_expiry(300)
  return HttpResponse(email)

@auto
def record(request):
  """
  用户购买记录
  :param request:
  :return:
  """
  is_super, is_login = auto_is_login(request)
  purchased_data = ''
  msg_tag = ''
  if request.method == 'GET':
    email = request.session.get('username')
    user_self_data = select(email)
    try:
      user_info = models.UserInfo.objects.filter(user_email=email).first()
      purchased_data = eval(user_info.purchased)
    except AttributeError:
      msg_tag = '0'
  return render(request, 'record.html', {'is_login': is_login, 'data': purchased_data, \
                                         'msg_tag': msg_tag, 'user_self_data': user_self_data})

@auto
def modify_user_info(request):
  """
  修改用户的信息
  :param request:
  :return:
  """
  if request.method == "POST":
    email = request.session.get('username')
    tel = request.POST.get('tel')
    old_passwd = request.POST.get('oldPasswd')
    new_passwd1 = request.POST.get('newPasswd1')
    new_passwd2 = request.POST.get('newPasswd2')
    if tel:
      modify_user_self_info.modifyTel(email, tel)
    if old_passwd and new_passwd2 and new_passwd1:
      modify_user_self_info.modifyPwd(email, old_passwd, new_passwd1, new_passwd2)
  return redirect('/record')

def domain_detail_info(request, nid):
  """
  获取域名的详细信息
  :param request:
  :param nid: 域名的id号
  :return:
  """
  # 判断用户是否登录
  is_super, is_login = auto_is_login(request)
  error = ''
  domain_info_list, domain_transaction = '', ''
  if request.method == "GET":
    if nid:
      nid = int(nid)
      db_domain_info = models.DomainList.objects.filter(id=nid).first()
      if db_domain_info:
        domain_info_list,domain_transaction = select_domain.option_doamin_info(nid, 1)
        if domain_info_list == 'error':
          return redirect('/index')
      else:
        error = '没有找到域名的信息'
    else:
      return redirect('/index')
  return render(request,'domain_detail_info.html', {'is_login': is_login, 'is_super': is_super,\
                                                    'domain_info':domain_info_list,\
                                                    'error':error, 'transaction':domain_transaction,
                                                    'id':nid
                                                    })

@auto
def domain_registered(request):
  """
  域名抢注页面处理
  :param request:
  :return:
  """
  id = ''
  is_super, is_login = auto_is_login(request)
  if request.method == "GET":
    id = request.GET.get('id')
    if id:
      domain_info_dic,transaction = select_domain.option_doamin_info(id, 1)
      if domain_info_dic == 'error':
        return redirect('/index')
      if transaction == '0':
        max_info, totle, domain_name = registered_main.reistered_info_option(id, 1)
        try:
          db_reistered = models.Registered.objects.filter(domain_name=domain_name).first()
          base_tolte = str(db_reistered.base_totle)
          base_price = str(db_reistered.base_price)
          if base_tolte and base_tolte.isdecimal():
            base_tolte = int(base_tolte)
          else:
            base_tolte = 0
          if base_price and base_price.isdecimal():
            base_price = base_price
          else:
            base_price = 0
          base_price = float(base_price)
          if base_price:
            max_info['price'] = base_price
          else:
            max_info['price'] = int(max_info.get('price')) + base_price
          totle = totle + base_tolte
        except AttributeError:
          base_price = 0
        if max_info:
          max_price = float(max_info.get('price'))
        else:
          max_price = 0
    else:
      return redirect('/index')
  if request.method == "POST":
    path = request.get_raw_uri()
    user_name = request.session.get('username')
    domainName = request.POST.get('domainName')
    email = request.POST.get('email')
    tel = request.POST.get('tel')
    wechat = request.POST.get('wechat')
    price = request.POST.get('price')
    if user_name and domainName and tel and price and email:
      db_search = models.Registered.objects.filter(domain_name=domainName).first()
      if db_search:
        registered_info_str = db_search.registered_info
        registered_info_dic = eval(registered_info_str)
        info_dic = {
          'email': email,
          'tel': tel,
          'wechat': wechat,
          'price': price
        }
        registered_info_dic[user_name] = info_dic
        models.Registered.objects.filter(domain_name=domainName).update(registered_info=registered_info_dic)
        now_info = '参与成功'
      else:
        registered_info_dic = {}
        info_dic = {
          'email': email,
          'tel': tel,
          'wechat': wechat,
          'price': price,
        }
        registered_info_dic[user_name] = info_dic
        db_create_dic = {
          'domain_name': domainName,
          'registered_info': registered_info_dic,
          'status': 1
        }
        models.Registered.objects.create(**db_create_dic)
        if models.Registered.objects.filter(domain_name=domainName).first():
          now_info = '参与成功'
        else:
          now_info = '参与失败请重试'
    else:
      return redirect(path)
    return HttpResponse("""<!DOCTYPE html>
                              <html lang="en">
                              <head>
                                <meta charset="UTF-8">
                                <meta http-equiv='Refresh' Content='0.1'; Url='/admin'/>
                              </head>
                              <body>
                                  <p style='text-align: center;'>点击后,将跳转首页面</p>
                                  <script>
                                    window.alert('%s');
                                  </script>
                              </body>
                              </html>""" %(now_info))
  return render(request, 'registered.html', {'is_login': is_login, 'is_super': is_super, \
                                              'id':id, 'domain_name': domain_name, 'totle': totle,
                                              'max_price': max_price,
                                               })

def pay():
  """
  初始化Alipay
  :return:
  """
  config_info = config.aliPayCondfig()
  app_private_key_string = open(config_info.get('merchant_private_key_path')).read()
  alipay_public_key_string = open(config_info.get('alipay_public_key_path')).read()

  alipay = AliPay(
    appid=config_info.get('app_id'),
    app_notify_url=config_info.get('notify_url'),
    app_private_key_string=app_private_key_string,
    alipay_public_key_string=alipay_public_key_string,  # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥
    debug=True,  # 默认False,配合沙箱模式使用
    sign_type="RSA"  # RSA 或者 RSA2
  )
  return alipay

@auto
def domain_reserve(request):
  """
  预定域名处理
  :param request:
  :return:
  """
  if request.method == "GET":
    nid = request.GET.get('id', None)
    if nid:
      db_info = models.DomainList.objects.filter(id=nid).first()
      if db_info:
        domain_name = db_info.domain_name
        buyType = str(db_info.transaction_type)
        status = str(db_info.status)
        if buyType == '1' and status == '0':
          domain_info = db_info.domain_info
          info = eval(domain_info)
          try:
            price = float(info.get('价格'))
          except (ValueError):
            price = -1
          if price >= 0:
            user_id = str(request.session.get('user_id'))
            alipay = pay()
            config_info = config.aliPayCondfig()
            query_params = alipay.api_alipay_trade_page_pay(
              subject= '{}'.format(domain_name), #商品简单描述
              out_trade_no= user_id + '.' + str(time.time()),  #商品订单编号
              total_amount= price, #交易金额(单位：元 保留两位小数)
              return_url = config_info.get('return_url'),
              timeout_express= '60m'
            )
            # 支付宝网关链接，去掉dev就是生产环境了
            if config_info.get('debug'):
              pay_url = "https://openapi.alipay.com/gateway.do?{}".format(query_params)
            else:
              pay_url = "https://openapi.alipaydev.com/gateway.do?{}".format(query_params)
            return redirect(pay_url)
  return redirect('/index')

def payNotify(request):
  """
  处理支付宝返回的结果 POST
  :param requests:
  :return:
  """
  alipay = pay()
  if request.method == "POST":
    data_dict = request.POST.dict()
    sign = data_dict.pop('sign', None)
    status = alipay.verify(data_dict, sign)
    if status:
      trade_status = data_dict.get('trade_status')
      if trade_status in ('TRADE_SUCCESS', 'TRADE_FINISHED'):
        order = data_dict.get('out_trade_no')
        price = data_dict.get('receipt_amount')
        domain_name = data_dict.get('subject')
        if order and price and domain_name:
          #基本参数
          buy_type = '一口价'
          user_id = int(order.split('.')[0])
          now_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
          #获取用户的的信息
          db_user_info = models.UsersList.objects.filter(id=user_id).first()
          user_email = db_user_info.user_email
          user_tel = db_user_info.phone
          #获取domain的信息
          db_domain = models.DomainList.objects.filter(domain_name=domain_name).first()
          domain_id = db_domain.id
          #写入用的的购买记录
          buyHistory.option_buyHistory(domain_id, domain_name, user_email, now_time, buy_type, price)
          #修改域名信息状态
          modify_domain.modifyStatus(1, domain=domain_name)
          #将购买信息写入到管理员清单
          reserve_dic = {
            'domain_name': domain_name,
            'user_email': user_email,
            'user_tel': user_tel,
            'order_number': order,
            'transaction_time': now_time,
            'transaction_price': price
          }
          models.Reserve.objects.create(**reserve_dic)
          send_email.send_reserve_info(user_name=user_email,
                                       user_tel=user_tel,
                                       domain_name=domain_name,
                                       price=price,
                                       now_time=now_time)
  return HttpResponse('post')

@auto
def payReturn(request):
  """
  处理支付宝返回的结果
  POST
  :param
  requests:
  :return:
  """
  alipay = pay()
  if request.method == "GET":
    """返回用户的交易信息状态"""
    params = request.GET.dict()
    sign = params.pop('sign')
    status = alipay.verify(params, sign)
    if status:
      return HttpResponse("""<!DOCTYPE html>
                                <html lang="en">
                                <head>
                                <meta charset="UTF-8">
                                <title>success</title>
                                </head>
                                <body>
                                <h1>&nbsp;</h1>
                                <h1>&nbsp;</h1>
                                <h3 style="text-align: center;"><a href='/index' style="text-decoration: none; color: black;">交易成功 ╰(￣▽￣)╮,请等待管理员联系您(点击返回主页)</a></h3>
                                </body>
                                </html>""")
    else:
      return HttpResponse("""<!DOCTYPE html>
                                <html lang="en">
                                <head>
                                  <meta charset="UTF-8">
                                  <title>success</title>
                                </head>
                                <body>
                                  <h1>&nbsp;</h1>
                                  <h1>&nbsp;</h1>
                                  <h3 style="text-align: center;"><a href='/index' style="text-decoration: none; color: black;">交易失败(づ╥﹏╥)づ (点击返回主页)</a></h3>
                                </body>
                                </html>""")

  return redirect('/index')

#admin views
@auto_super
def admin(request):
  """
  管理员主页处理
  :param request:
  :return:
  """
  email = request.session.get('username')
  user_info_dict = select(email)
  if request.method == "GET":
    page_num = request.GET.get('p', '1')  # 获取p的数值(页数)
    if not page_num.isdecimal():
      page_num = 1
    totle_page = select_domain.get_pages()
    page_num = int(page_num)
    if page_num > totle_page:
      page_num = totle_page
    page_list = select_domain.get_page_list(page_num, totle_page)
    domain_dic = select_domain.get_domian_info(page_num)
  return render(request, 'admin/admin_index.html', {'user_info_dict': user_info_dict,
                                                    'domain_dic': domain_dic, 'page_list': page_list, \
                                                    'totle_page': totle_page, 'now_page': page_num
                                                    })

@auto_super
def admin_reinfo(request):
  """
  管理员修改个人信息
  :param request:
  :return:
  """
  if request.method == "POST":
    email = request.session.get('username')
    new_email = request.POST.get('email')
    tel = request.POST.get('tel')
    old_passwd = request.POST.get('oldPasswd')
    newPasswd1 = request.POST.get('newPasswd1')
    newPasswd2 = request.POST.get('newPasswd2')
    if new_email:
      sing = modify_user_self_info.modifyEmail(email, new_email)
      if sing == '1':
        request.session['username'] = new_email
        modify_user_self_info.modifyPwd(new_email, old_passwd, newPasswd1, newPasswd2)
      if old_passwd and newPasswd1 and newPasswd2:
        modify_user_self_info.modifyPwd(new_email, old_passwd, newPasswd1, newPasswd2)
      if tel:
        modify_user_self_info.modifyTel(new_email, tel)
    else:
      if old_passwd and newPasswd1 and newPasswd2:
        modify_user_self_info.modifyPwd(email, old_passwd, newPasswd1, newPasswd2)
      if tel:
        modify_user_self_info.modifyTel(email, tel)
  return redirect('/admin')

@auto_super
def admin_domain_update(request):
  """
  批量上传域名
  :param request:
  :return:
  """

  if request.method == "POST":
    try:
      file_obj = request.FILES.get('excel-file')
      filename = file_obj.name
    except AttributeError:
      return redirect('/admin', )
    if filename.endswith(r'.xlsx') or filename.endswith(r'.xls'):
      file_path = os.path.join('upload', filename)
      with open(file_path, 'wb') as f:
        for file_body in file_obj.chunks():
          f.write(file_body)
      update_status = updateDomain(file_path)
      if update_status == '1':
        return HttpResponse("""<!DOCTYPE html>
                                      <html lang="en">
                                      <head>
                                        <meta charset="UTF-8">
                                        <meta http-equiv='Refresh' Content='0.1'; Url='/admin'/>
                                      </head>
                                      <body>
                                          <p style='text-align: center;'>点击后,将跳转回原页面</p>
                                          <script>
                                            alert('域名写入成功');
                                          </script>
                                      </body>
                            </html>""")
      else:
        return HttpResponse("""<!DOCTYPE html>
                              <html lang="en">
                              <head>
                                <meta charset="UTF-8">
                                <meta http-equiv='Refresh' Content='0.1'; Url='/admin'/>
                              </head>
                              <body>
                                  <p style='text-align: center;'>点击后,将跳转回原页面</p>
                                  <script>
                                    alert('域名写入失败');
                                  </script>
                              </body>
                              </html>""")
    else:
      return HttpResponse("""<!DOCTYPE html>
                              <html lang="en">
                              <head>
                                <meta charset="UTF-8">
                                <meta http-equiv='Refresh' Content='0.1'; Url='/admin'/>
                              </head>
                              <body>

                                  <p style='text-align: center;'>点击后,将跳转回原页面</p>
                                  <script>
                                    alert('文件格式不正确');
                                  </script>
                              </body>
                              </html>""")
  return redirect('/admin',)

@auto_super
def admin_addDomain(request):
  """
  单条添加域名
  :param requets:
  :return:
  """
  if request.method == "POST":
    domain_name = request.POST.get('domain', None)
    if domain_name:
      if models.DomainList.objects.filter(domain_name=domain_name).first():
        return HttpResponse("""<!DOCTYPE html>
                                      <html lang="en">
                                      <head>
                                        <meta charset="UTF-8">
                                        <meta http-equiv='Refresh' Content='0.1'; Url='/admin'/>
                                      </head>
                                      <body>
                                          <p style='text-align: center;'>点击后,将跳转回原页面</p>
                                          <script>
                                            alert('域名已存在');
                                          </script>
                                      </body>
                            </html>""")
      else:
        domain_info_dic = {
          '备案，文字说明': request.POST.get('domainExplain', ''),
          '交易类型': request.POST.get('transactionType', ''),
          '域名类型': request.POST.get('domainType', ''),
          '长度': request.POST.get('domainlLength', ''),
          '评分': request.POST.get('domainScore', ''),
          '估价': request.POST.get('domainEvaluation', ''),
          '历史量': request.POST.get('domainHistory', ''),
          'alexa': request.POST.get('domainAlexa', ''),
          '反链': request.POST.get('AntiChain', ''),
          '外链': request.POST.get('TheChain', ''),
          '收录量': request.POST.get('domainAmount', ''),
          'pr': request.POST.get('domainPr', ''),
          '权重': request.POST.get('domainWeight', ''),
          '注册年限': request.POST.get('domainReTime', ''),
          '剩余时间': request.POST.get('RemainingTime', ''),
          '价格': request.POST.get('domainPrice', ''),
        }
        db_create_dic = {
          'domain_name': domain_name,
          'domain_info': domain_info_dic,
          'domain_type': request.POST.get('domainType', ''),
          'status': 0,
          'transaction_type': request.POST.get('transactionType', '2')
        }
        models.DomainList.objects.create(**db_create_dic)
        if models.DomainList.objects.filter(domain_name=domain_name).first():
          return HttpResponse("""<!DOCTYPE html>
                                                <html lang="en">
                                                <head>
                                                  <meta charset="UTF-8">
                                                  <meta http-equiv='Refresh' Content='0.1'; Url='/admin'/>
                                                </head>
                                                <body>
                                                    <p style='text-align: center;'>点击后,将跳转回原页面</p>
                                                    <script>
                                                      alert('域名添加成功');
                                                    </script>
                                                </body>
                                      </html>""")
        else:
          return HttpResponse("""<!DOCTYPE html>
                                      <html lang="en">
                                      <head>
                                        <meta charset="UTF-8">
                                        <meta http-equiv='Refresh' Content='0.1'; Url='/admin'/>
                                      </head>
                                      <body>
                                          <p style='text-align: center;'>点击后,将跳转回原页面</p>
                                          <script>
                                            alert('域名添加失败');
                                          </script>
                                      </body>
                            </html>""")
  return redirect('/admin')

@auto_super
def admin_delDomain(request):
  """
  删除域名
  :param request:
  :return:
  """
  if request.method == "GET":
    id = request.GET.get('id',None)
    if id:
      if models.DomainList.objects.filter(id=id).first():
        models.DomainList.objects.filter(id=id).delete()
  return redirect('/admin')

@auto_super
def admin_modifyDomain(request):
  """
  修改域名信息
  :param request:
  :return:
  """
  id = request.GET.get('id')
  if id:
    if models.DomainList.objects.filter(id=id).first():
      domain_dic = select_domain.option_one_domain(id)
    else:
      return redirect('/admin')
  if request.method == "POST":
    domain_name = request.POST.get('domain_name', None)
    domain_id = request.POST.get('domain_id', None)
    if domain_name and domain_id:
      domain_status = request.POST.get('domainStatus')
      domain_info_dic = {
        '备案，文字说明': request.POST.get('domainExplain', None),
        '交易类型': request.POST.get('transactionType', None),
        '域名类型': request.POST.get('domainType', None),
        '长度': request.POST.get('domainlLength', None),
        '评分': request.POST.get('domainScore', None),
        '估价': request.POST.get('domainEvaluation', None),
        '历史量': request.POST.get('domainHistory', None),
        'alexa': request.POST.get('domainAlexa', None),
        '反链': request.POST.get('AntiChain', None),
        '外链': request.POST.get('TheChain', None),
        '收录量': request.POST.get('domainAmount', None),
        'pr': request.POST.get('domainPr', None),
        '权重': request.POST.get('domainWeight', None),
        '注册年限': request.POST.get('domainReTime', None),
        '剩余时间': request.POST.get('RemainingTime', None),
        '价格': request.POST.get('domainPrice', None),
      }
      db_domain_dic = select_domain.option_doamin_info(domain_id)
      db_domain_info = db_domain_dic.get('info')
      keys_list = db_domain_info.keys()
      for key in keys_list:
        if not domain_info_dic.get(key):
          continue
        if db_domain_info.get(key) !=  domain_info_dic.get(key):
          db_domain_info[key] = domain_info_dic.get(key)
      models.DomainList.objects.filter(domain_name=domain_name).update(domain_info=db_domain_info)
      if db_domain_dic.get('status') != domain_status:
        models.DomainList.objects.filter(domain_name=domain_name).update(status=domain_status)
      post_transactionType = request.POST.get('transactionType', None)
      if post_transactionType:
        if post_transactionType != models.DomainList.objects.filter(domain_name=domain_name).first().transaction_type:
          models.DomainList.objects.filter(domain_name=domain_name).update(transaction_type=post_transactionType)
      post_domain_type = request.POST.get('domainType', None)
      if post_domain_type:
        if post_domain_type != models.DomainList.objects.filter(domain_name=domain_name).first().domain_type:
          models.DomainList.objects.filter(domain_name=domain_name).update(domain_type=post_domain_type)
    else:
      return redirect('/admin')
    return redirect('/admin/modify?id=' + domain_id)
  return render(request, 'admin/admin_modifyDomain.html', {'domain_dic':domain_dic})

@auto_super
def admin_registered_list(request):
  """
  正在抢注的域名清单
  :param request:
  :return:
  """
  if request.method == "GET":
    db_info = models.Registered.objects.all()
    reponse_dic = {}
    for one_info in db_info:
      domain_name = one_info.domain_name
      domain_id = models.DomainList.objects.filter(domain_name=domain_name).first().id
      max_info, totle, domain_name = registered_main.reistered_info_option(domain_id)
      if len(max_info) == 0:
        reponse_dic[domain_name] = {
          'domain_id': domain_id,
          'totle': '0',
          'max_price': '0'
        }
      else:
        max_price = max_info.get('price')
        reponse_dic[domain_name] = {
          'domain_id': domain_id,
          'totle': totle,
          'max_price': max_price
        }
  return render(request, 'admin/admin_registered_list.html', {'info_list': reponse_dic})

@auto_super
def admin_registered_info(request):
  """
  单个域名抢注的详细信息
  :param request:
  :return:
  """
  nid = request.GET.get('id', None)
  if nid and nid.isdecimal():
    db_is_exist_DL = models.DomainList.objects.filter(id=nid).first()
    if db_is_exist_DL:
      domain_name = db_is_exist_DL.domain_name
      db_is_exist_RD = models.Registered.objects.filter(domain_name=domain_name).first()
      if db_is_exist_RD:
        db_info_dic = db_is_exist_RD.registered_info
        sort_userList, info_dic = sort_registered.sortInfoMain(db_info_dic)
        now_status = db_is_exist_RD.status
        if not sort_userList and not info_dic:
          sort_userList, info_dic = 'error', 'error'
      else:
        return redirect('/admin/registered-list')
    else:
      return redirect('/admin/registered-list')
  else:
    return redirect('/admin/registered-list')
  return render(request, 'admin/admin_registered_info.html', {'domain_name': domain_name, \
                                                              'sort_list': sort_userList,\
                                                              'info_dic': info_dic, 'status': str(now_status)})

@auto_super
def admin_reserve_list(request):
  """
  域名预约清单
  :param request:
  :return:
  """
  if request.method == "GET":
    db_info = models.Reserve.objects.all()
    info_list_dic = {}
    for one_info in db_info:
      domain_name = one_info.domain_name
      tmp_info = {
        'user_id': one_info.user_email,
        'user_tel': one_info.user_tel,
        'order_number': one_info.order_number,
        'transzction_time': one_info.transaction_time,
        'transzction_price': one_info.transaction_price
      }
      info_list_dic[domain_name] = tmp_info
  return render(request, 'admin/admin_reserve_list.html', {'info_list_dic': info_list_dic})

@auto_super
def admin_delRegistered(request):
  """
  删除正在抢注的域名
  :param request:
  :return:
  """
  if request.method == "POST":
    domain_name = request.POST.get('domain_name')
    db_exist = models.Registered.objects.filter(domain_name=domain_name).first()
    if db_exist:
      models.Registered.objects.filter(domain_name=domain_name).delete()
      if not models.Registered.objects.filter(domain_name=domain_name).first():
        return HttpResponse('succes')
  return HttpResponse('fail')

@auto_super
def admin_endRegistered(request):
  """
  结束一个域名的抢注
  :param request:
  :return:
  """
  if request.method == "POST":
    domain_name = request.POST.get('domain_name')
    now_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
    db_seacrh_DL = models.DomainList.objects.filter(domain_name=domain_name).first()
    buy_type = '竞价'
    if db_seacrh_DL:
      nid = db_seacrh_DL.id
    else:
      nid = None
    db_search_RE = models.Registered.objects.filter(domain_name=domain_name).first()
    if db_search_RE:
      dic = db_search_RE.registered_info
      sort_userList, info_dic = sort_registered.sortInfoMain(dic)
      if not sort_userList:
        models.Registered.objects.filter(domain_name=domain_name).delete()
        return HttpResponse('sucess')
      user_name = sort_userList[0]
      price = info_dic.get(user_name).get('price')
    else:
      user_name = None
      price = None
    buyHistory.option_buyHistory(nid,domain_name, user_name, now_time, buy_type, price)
    models.Registered.objects.filter(domain_name=domain_name).update(status=0)
    modify_domain.modifyStatus(1, domain=domain_name)
    return HttpResponse('success')
  return HttpResponse('fail')

@auto_super
def admin_addBase(request):
  """
  添加抢注域名的基值
  :param request:
  :return:
  """
  if request.method == "POST":
    domain_name = request.POST.get('addDoaminName',None)
    domain_baseTotle = request.POST.get('addBaseTotle', None)
    domain_basePrice = request.POST.get('addBasePrice', None)
    if domain_name:
      if (domain_basePrice and domain_basePrice.isdecimal()) \
              or (domain_baseTotle and domain_baseTotle.isdecimal()):
        db_is_exist_domain = models.DomainList.objects.filter(domain_name=domain_name).first()
        re_db_is_exists = models.Registered.objects.filter(domain_name=domain_name).first()
        if db_is_exist_domain:
          if re_db_is_exists:
            if domain_baseTotle and domain_baseTotle != str(re_db_is_exists.base_totle):
              models.Registered.objects.filter(domain_name=domain_name).update(base_totle=domain_baseTotle)
            if domain_basePrice and domain_basePrice != str(re_db_is_exists.base_price):
              models.Registered.objects.filter(domain_name=domain_name).update(base_price=domain_basePrice)
          else:
            create_dic = {
              'domain_name': domain_name,
              'registered_info': {},
              'base_totle': domain_baseTotle,
              'base_price': domain_baseTotle,
              'status': 1
            }
            models.Registered.objects.create(**create_dic)
            modify_domain.modifyStatus(0, domain=domain_name)
            modify_domain.modifyTransaction(0, domain=domain_name)
  return redirect('/admin/registered-list')
